﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<style>
    .add-form-container {
        padding: 20px;
        max-height: 800px;
        overflow-y: auto;
        background: #fff;
    }
    
    .form-section {
        margin-bottom: 25px;
    }
    
    .form-row {
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 15px;
        align-items: center;
    }
    
    .form-group {
        display: flex;
        align-items: center;
        margin-right: 30px;
        margin-bottom: 10px;
    }
    
    .form-group.full-width {
        width: 100%;
        margin-right: 0;
    }
    
    .layui-form-label {
        width: 100px;
        padding: 9px 15px;
        font-size: 14px;
    }
    
    .layui-input-inline {
        width: 180px;
    }
    
    .layui-input-inline.wide {
        width: 250px;
    }
    
    .layui-textarea {
        min-height: 80px;
    }
    
    /* 自动生成开关样式 */
    .auto-generate-switch {
        margin-left: 10px;
        position: relative;
    }
    
    .switch-container {
        display: inline-flex;
        align-items: center;
        background: #f0f0f0;
        border-radius: 20px;
        padding: 2px;
        cursor: pointer;
        transition: all 0.3s ease;
        width: 80px;
        height: 32px;
    }
    
    .switch-container.active {
        background: #5FB878;
    }
    
    .switch-slider {
        width: 28px;
        height: 28px;
        background: white;
        border-radius: 50%;
        transition: all 0.3s ease;
        box-shadow: 0 2px 4px rgba(0,0,0,0.2);
    }
    
    .switch-container.active .switch-slider {
        transform: translateX(48px);
    }
    
    .switch-text {
        position: absolute;
        font-size: 12px;
        color: #666;
        transition: all 0.3s ease;
    }
    
    .switch-text.off {
        left: 8px;
    }
    
    .switch-text.on {
        right: 8px;
        color: white;
    }
    
    .switch-container.active .switch-text.off {
        opacity: 0;
    }
    
    .switch-container:not(.active) .switch-text.on {
        opacity: 0;
    }
    
    /* 数量控制按钮 */
    .qty-controls {
        display: flex;
        align-items: center;
    }
    
    .qty-btn {
        width: 30px;
        height: 30px;
        line-height: 28px;
        text-align: center;
        border: 1px solid #e6e6e6;
        background: #fff;
        cursor: pointer;
        user-select: none;
        font-size: 16px;
        color: #666;
    }
    
    .qty-btn:hover {
        background: #f2f2f2;
        color: #333;
    }
    
    .qty-input {
        width: 80px;
        text-align: center;
        border-left: none;
        border-right: none;
    }
    

    
    /* 操作按钮区域 */
    .form-actions {
        text-align: center;
        margin-top: 30px;
        padding-top: 20px;
        border-top: 1px solid #e6e6e6;
    }
    
    .form-actions .layui-btn {
        margin: 0 10px;
        min-width: 100px;
    }
</style>
<body>
    <div class="add-form-container">
        <form class="layui-form" id="addInspectionForm" lay-filter="addInspectionForm">
            @Html.AntiForgeryToken()
            
            <!-- 检验单基本信息 -->
            <div class="form-section">
                <div class="form-row">
                    <div class="form-group">
                        <label class="layui-form-label"><span style="color: red;">*</span> 检验单编号:</label>
                        <div class="layui-input-inline">
                            <input type="text" id="OutgoingCode" name="OutgoingCode" placeholder="请输入检验单编号" 
                                   autocomplete="off" class="layui-input" lay-verify="required">
                        </div>
                        <div class="auto-generate-switch">
                            <div class="switch-container" id="autoGenerateSwitch">
                                <div class="switch-slider"></div>
                                <span class="switch-text off">手动</span>
                                <span class="switch-text on">自动</span>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="layui-form-label">检验单名称:</label>
                        <div class="layui-input-inline">
                            <input type="text" id="OutgoingName" name="OutgoingName" placeholder="请输入内容" 
                                   autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>

            <!-- 产品信息 -->
            <div class="form-section">
                <div class="form-row">
                    <div class="form-group">
                        <label class="layui-form-label"><span style="color: red;">*</span> 产品编码:</label>
                        <div class="layui-input-inline">
                            <input type="text" id="ProductCode" name="ProductCode" placeholder="请输入或选择产品编码" 
                                   autocomplete="off" class="layui-input" lay-verify="required">
                        </div>
                        <div class="auto-generate-switch">
                            <div class="switch-container" id="productCodeAutoGenerateSwitch">
                                <div class="switch-slider"></div>
                                <span class="switch-text off">手动</span>
                                <span class="switch-text on">自动</span>
                            </div>
                        </div>
@*                         <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" onclick="selectProduct()" style="margin-left: 10px;">
                            <i class="layui-icon layui-icon-search"></i> 选择
                        </button> *@
                    </div>
                    <div class="form-group">
                        <label class="layui-form-label">产品名称:</label>
                        <div class="layui-input-inline">
                            <input type="text" id="ProductName" name="ProductName" placeholder="请输入产品名称" 
                                   autocomplete="off" class="layui-input">
                        </div>
                    </div>
                                        <div class="form-group">
                        <label class="layui-form-label"><span style="color: red;">*</span> 单位:</label>
                        <div class="layui-input-inline">
                            <select name="Unitt" id="Unitt" lay-filter="unitSelect" lay-verify="required">
                                <option value="">请选择单位</option>
                                <option value="kg">kg</option>
                                <option value="g">g</option>
                                <option value="斤">斤</option>
                                <option value="袋">袋</option>
                                <option value="个">个</option>
                                <option value="台">台</option>
                                <option value="米">米</option>
                                <option value="升">升</option>
                            </select>
                        </div>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group full-width">
                        <label class="layui-form-label">规格型号:</label>
                        <div class="layui-input-inline">
                            <input type="text" id="Specifications" name="Specifications" placeholder="请输入规格型号"
                                   autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>

            <!-- 客户信息 -->
            <div class="form-section">
                <div class="form-row">
                    <div class="form-group">
                        <label class="layui-form-label"><span style="color: red;">*</span> 客户编码:</label>
                        <div class="layui-input-inline">
                            <input type="text" id="CustomerCode" name="CustomerCode" placeholder="请选择客户" 
                                   autocomplete="off" class="layui-input">
                        </div>
                        <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" onclick="selectCustomer()" style="margin-left: 10px;">
                            <i class="layui-icon layui-icon-search"></i> 选择
                        </button>
                    </div>
                    <div class="form-group">
                        <label class="layui-form-label"><span style="color: red;">*</span> 客户名称:</label>
                        <div class="layui-input-inline">
                            <input type="text" id="CustomerName" name="CustomerName" placeholder="请输入客户名称" 
                                   autocomplete="off" class="layui-input" lay-verify="required">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="layui-form-label">批次号:</label>
                        <div class="layui-input-inline">
                            <input type="text" id="Batch" name="Batch" placeholder="请输入批次号" 
                                   autocomplete="off" class="layui-input">
                        </div>
                        <div class="auto-generate-switch">
                            <div class="switch-container" id="batchAutoGenerateSwitch">
                                <div class="switch-slider"></div>
                                <span class="switch-text off">手动</span>
                                <span class="switch-text on">自动</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 数量信息 -->
            <div class="form-section">
                <div class="form-row">
                    <div class="form-group">
                        <label class="layui-form-label"><span style="color: red;">*</span> 发货数量:</label>
                        <div class="qty-controls">
                            <span class="qty-btn" onclick="decreaseQty('SendNum')">-</span>
                            <input type="number" id="SendNum" name="SendNum" value="1" min="1" 
                                   class="layui-input qty-input" lay-verify="required">
                            <span class="qty-btn" onclick="increaseQty('SendNum')">+</span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="layui-form-label"><span style="color: red;">*</span> 检测数量:</label>
                        <div class="qty-controls">
                            <span class="qty-btn" onclick="decreaseQty('TestingNum')">-</span>
                            <input type="number" id="TestingNum" name="TestingNum" value="1" min="1" 
                                   class="layui-input qty-input" lay-verify="required">
                            <span class="qty-btn" onclick="increaseQty('TestingNum')">+</span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="layui-form-label">不合格数量:</label>
                        <div class="qty-controls">
                            <span class="qty-btn" onclick="decreaseQty('UnqualifiedNum')">-</span>
                            <input type="number" id="UnqualifiedNum" name="UnqualifiedNum" value="0" min="0" 
                                   class="layui-input qty-input">
                            <span class="qty-btn" onclick="increaseQty('UnqualifiedNum')">+</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 日期和检测信息 -->
            <div class="form-section">
                <div class="form-row">
                    <div class="form-group">
                        <label class="layui-form-label"><span style="color: red;">*</span> 出货日期:</label>
                        <div class="layui-input-inline">
                            <input type="text" id="ShipmentDate" name="ShipmentDate" placeholder="请选择出货日期" 
                                   autocomplete="off" class="layui-input" lay-verify="required">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="layui-form-label"><span style="color: red;">*</span> 检测日期:</label>
                        <div class="layui-input-inline">
                            <input type="text" id="TestingDate" name="TestingDate" placeholder="请选择检测日期" 
                                   autocomplete="off" class="layui-input" lay-verify="required">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="layui-form-label">检测结果:</label>
                        <div class="layui-input-inline">
                            <select id="TestingResult" name="TestingResult" lay-filter="testingResult">
                                <option value="">请选择检测结果</option>
                                <option value="合格">合格</option>
                                <option value="不合格">不合格</option>
                                <option value="待检测">待检测</option>
                            </select>
                        </div>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="layui-form-label">检测人员:</label>
                        <div class="layui-input-inline">
                            <input type="text" id="TestingPerson" name="TestingPerson" placeholder="请输入检测人员" 
                                   autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label class="layui-form-label">单据状态:</label>
                    <div class="layui-input-inline">
                        <select name="State" id="State">
                            <option value="">请选择</option>
                            <option value="0">草稿</option>
                            <option value="1">已确认</option>
                            <option value="2">已完成</option>
                        </select>
                    </div>
                </div>
            </div>
            <!-- 操作按钮 -->
            <div class="form-actions">
                <button type="submit" class="layui-btn layui-btn-normal" lay-submit lay-filter="submitForm">
                    <i class="layui-icon layui-icon-ok"></i> 保存
                </button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="parent.layer.closeAll()">
                    <i class="layui-icon layui-icon-close"></i> 取消
                </button>
            </div>
        </form>
    </div>
</body>
<script src="~/scripts/jquery-3.4.1.min.js"></script>
<script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
<script>
layui.use(['form', 'laydate', 'element'], function() {
    var form = layui.form;
    var laydate = layui.laydate;
    var element = layui.element;

    // 日期选择器
    laydate.render({
        elem: '#ShipmentDate',
        type: 'date',
        format: 'yyyy-MM-dd',
        value: new Date()
    });

    laydate.render({
        elem: '#TestingDate',
        type: 'date',
        format: 'yyyy-MM-dd',
        value: new Date()
    });

    // 自动生成状态
    var isAutoGenerate = false;
    var isProductCodeAutoGenerate = false;
    var isBatchAutoGenerate = false;

    // 自动生成开关点击事件
    $('#autoGenerateSwitch').click(function() {
        var $switch = $(this);
        var $input = $('#OutgoingCode');
        
        if (!isAutoGenerate) {
            // 开启自动生成
            isAutoGenerate = true;
            $switch.addClass('active');
            $input.prop('readonly', true).attr('placeholder', '系统自动生成编号');
            generateInspectionCode();
        } else {
            // 关闭自动生成
            isAutoGenerate = false;
            $switch.removeClass('active');
            $input.prop('readonly', false).val('').attr('placeholder', '请输入检验单编号').focus();
            layer.msg('已切换到手动输入模式', {icon: 1, time: 1500});
        }
    });

    // 产品编码自动生成开关点击事件
    $('#productCodeAutoGenerateSwitch').click(function() {
        var $switch = $(this);
        var $input = $('#ProductCode');
        
        if (!isProductCodeAutoGenerate) {
            // 开启自动生成
            isProductCodeAutoGenerate = true;
            $switch.addClass('active');
            $input.prop('readonly', true).attr('placeholder', '系统自动生成产品编码');
            generateProductCode();
        } else {
            // 关闭自动生成
            isProductCodeAutoGenerate = false;
            $switch.removeClass('active');
            $input.prop('readonly', false).val('').attr('placeholder', '请输入或选择产品编码').focus();
            layer.msg('已切换到手动输入模式', {icon: 1, time: 1500});
        }
    });

    // 批次号自动生成开关点击事件
    $('#batchAutoGenerateSwitch').click(function() {
        var $switch = $(this);
        var $input = $('#Batch');
        
        if (!isBatchAutoGenerate) {
            // 开启自动生成
            isBatchAutoGenerate = true;
            $switch.addClass('active');
            $input.prop('readonly', true).attr('placeholder', '系统自动生成批次号');
            generateBatchCode();
        } else {
            // 关闭自动生成
            isBatchAutoGenerate = false;
            $switch.removeClass('active');
            $input.prop('readonly', false).val('').attr('placeholder', '请输入批次号').focus();
            layer.msg('已切换到手动输入模式', {icon: 1, time: 1500});
        }
    });

    // 生成检验单编号（前端随机生成）
    function generateInspectionCode() {
        var $input = $('#OutgoingCode');
        var $switch = $('#autoGenerateSwitch');
        
        // 生成格式：OQC + 年月日 + 3位随机数
        var now = new Date();
        var year = now.getFullYear();
        var month = String(now.getMonth() + 1).padStart(2, '0');
        var day = String(now.getDate()).padStart(2, '0');
        var randomNum = String(Math.floor(Math.random() * 999) + 1).padStart(3, '0');
        
        var inspectionCode = 'OQC' + year + month + day + randomNum;
        
        // 直接填入编号
        $input.val(inspectionCode);
        layer.msg('编号生成成功: ' + inspectionCode, {icon: 1, time: 1500});
    }

    // 生成产品编码（前端随机生成）
    function generateProductCode() {
        var $input = $('#ProductCode');
        
        // 生成格式：PRD + 年月日 + 3位随机数
        var now = new Date();
        var year = now.getFullYear();
        var month = String(now.getMonth() + 1).padStart(2, '0');
        var day = String(now.getDate()).padStart(2, '0');
        var randomNum = String(Math.floor(Math.random() * 999) + 1).padStart(3, '0');
        
        var productCode = 'PRD' + year + month + day + randomNum;
        
        // 直接填入编号
        $input.val(productCode);
        layer.msg('产品编码生成成功: ' + productCode, {icon: 1, time: 1500});
    }

    // 生成批次号（前端随机生成）
    function generateBatchCode() {
        var $input = $('#Batch');
        
        // 生成格式：BAT + 年月日 + 3位随机数
        var now = new Date();
        var year = now.getFullYear();
        var month = String(now.getMonth() + 1).padStart(2, '0');
        var day = String(now.getDate()).padStart(2, '0');
        var randomNum = String(Math.floor(Math.random() * 999) + 1).padStart(3, '0');
        
        var batchCode = 'BAT' + year + month + day + randomNum;
        
        // 直接填入编号
        $input.val(batchCode);
        layer.msg('批次号生成成功: ' + batchCode, {icon: 1, time: 1500});
    }

    // 表单提交
    form.on('submit(submitForm)', function(data) {
        var formData = data.field;
        
        // 验证必填字段
        if (!formData.OutgoingCode || !formData.ProductCode || !formData.CustomerName || 
            !formData.SendNum || !formData.TestingNum || !formData.Unitt ||
            !formData.ShipmentDate || !formData.TestingDate) {
            layer.msg('请填写所有必填字段', {icon: 2});
            return false;
        }
        
        // 数据类型转换和验证
        formData.SendNum = parseInt(formData.SendNum) || 0;
        formData.TestingNum = parseInt(formData.TestingNum) || 0;
        formData.UnqualifiedNum = parseInt(formData.UnqualifiedNum) || 0;
        formData.State = parseInt(formData.State) || 1;
        
        // 验证数量逻辑
        if (formData.SendNum <= 0) {
            layer.msg('发货数量必须大于0', {icon: 2});
            return false;
        }
        
        if (formData.TestingNum <= 0) {
            layer.msg('检测数量必须大于0', {icon: 2});
            return false;
        }
        
        if (formData.UnqualifiedNum > formData.TestingNum) {
            layer.msg('不合格数量不能大于检测数量', {icon: 2});
            return false;
        }
        
        // 日期格式验证
        if (!isValidDate(formData.ShipmentDate)) {
            layer.msg('出货日期格式不正确', {icon: 2});
            return false;
        }
        
        if (!isValidDate(formData.TestingDate)) {
            layer.msg('检测日期格式不正确', {icon: 2});
            return false;
        }
        
        submitForm(formData);
        return false;
    });
    
    // 验证日期格式
    function isValidDate(dateString) {
        if (!dateString) return false;
        var regex = /^\d{4}-\d{2}-\d{2}$/;
        if (!regex.test(dateString)) return false;
        var date = new Date(dateString);
        return date instanceof Date && !isNaN(date);
    }
    
    // 产品编码输入事件监听（可选：输入时自动查询）
    $('#ProductCode').on('blur', function() {
        var productCode = $(this).val().trim();
        if (productCode) {
            // 这里可以添加根据产品编码自动查询产品信息的逻辑
            // queryProductInfo(productCode);
        }
    });

    // 提交表单数据
    function submitForm(formData) {
        // 显示加载提示
        var loadingIndex = layer.load(1, {
            shade: [0.3, '#000']
        });
        
        $.ajax({
            url: '/OutgoingInspection/AddOutgoingInspection',
            type: 'POST',
            data: formData,
            headers: {
                'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
            },
            success: function(result) {
                layer.close(loadingIndex);
                
                if (result && result > 0) {
                    layer.msg('保存成功！', {icon: 1, time: 1500}, function() {
                        // 关闭弹窗
                        parent.layer.closeAll();
                        
                        // 跳转到InspectionView视图并刷新数据
                        if (parent.window.location.pathname.indexOf('OutgoingInspection') === -1) {
                            // 如果当前不在检验页面，则跳转
                            parent.window.location.href = '/ProductionSystem/OutgoingInspection/InspectionView';
                        } else {
                            // 如果已经在检验页面，则刷新数据
                            if (parent.loadInspectionData && typeof parent.loadInspectionData === 'function') {
                                parent.loadInspectionData();
                            } else if (parent.searchInspectionData && typeof parent.searchInspectionData === 'function') {
                                parent.searchInspectionData();
                            } else {
                                // 如果没有找到刷新函数，则重新加载页面
                                parent.window.location.reload();
                            }
                        }
                    });
                } else {
                    layer.msg('保存失败，请检查数据后重试', {icon: 2, time: 2000});
                }
            },
            error: function(xhr, status, error) {
                layer.close(loadingIndex);
                console.error('保存出错:', xhr.responseText);
                
                var errorMsg = '网络异常，请稍后重试';
                if (xhr.status === 400) {
                    errorMsg = '数据格式错误，请检查输入内容';
                } else if (xhr.status === 500) {
                    errorMsg = '服务器内部错误，请联系管理员';
                }
                
                layer.msg(errorMsg, {icon: 2, time: 3000});
            }
        });
    }


    
    // 表单渲染
    form.render();
});

// 数量增减函数
function increaseQty(inputId) {
    var input = $('#' + inputId);
    var currentVal = parseInt(input.val()) || 0;
    input.val(currentVal + 1).trigger('input');
}

function decreaseQty(inputId) {
    var input = $('#' + inputId);
    var currentVal = parseInt(input.val()) || 0;
    if (currentVal > 0) {
        input.val(currentVal - 1).trigger('input');
    }
}

// 选择产品功能
function selectProduct() {
    layer.msg('产品选择功能开发中...', {icon: 1, time: 2000});
    // TODO: 这里可以打开产品选择弹窗
    // 示例代码：
    /*
    layer.open({
        type: 2,
        title: '选择产品',
        shadeClose: true,
        shade: 0.3,
        area: ['800px', '600px'],
        content: '/ProductionSystem/Product/SelectProduct',
        success: function(layero, index) {
            // 弹窗成功打开后的回调
        }
    });
    */
}

// 选择客户功能
function selectCustomer() {
    layer.open({
        type: 2,
        title: '客户选择',
        shadeClose: true,
        shade: 0.3,
        area: ['1400px', '900px'],
        content: '/OutgoingInspection/GetUserListView',
        success: function(layero, index) {
            // 弹窗成功打开后的回调
            console.log('客户选择弹窗已打开');
        }
    });
}

// 根据产品编码查询产品信息（示例函数）
function queryProductInfo(productCode) {
    if (!productCode) return;
    
    // 这里添加AJAX请求查询产品信息
    /*
    $.ajax({
        url: '/ProductionSystem/Product/GetProductInfo',
        type: 'GET',
        data: { productCode: productCode },
        success: function(result) {
            if (result && result.success) {
                $('#ProductName').val(result.data.productName || '');
                $('#Unitt').val(result.data.unit || '');
                $('#Specifications').val(result.data.specifications || '');
            }
        },
        error: function() {
            console.log('查询产品信息失败');
        }
    });
    */
}

// 设置产品信息（供外部调用）
function setProductInfo(productCode, productName, unit, specifications) {
    $('#ProductCode').val(productCode || '');
    $('#ProductName').val(productName || '');
    $('#Unitt').val(unit || '');
    $('#Specifications').val(specifications || '');
}

// 设置客户信息（供外部调用）
function setCustomerInfo(customerCode, customerName) {
    $('#CustomerCode').val(customerCode || '');
    $('#CustomerName').val(customerName || '');
    
    // 显示设置成功的提示
    if (customerCode && customerName) {
        layer.msg('客户信息设置成功：' + customerName, {icon: 1, time: 1500});
    }
}


</script>